package com.secondkill.redis;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by zhangkai12 on 2018/7/3.
 */
@Service
public class RedisService {
    @Autowired
    JedisPool jedisPool;


    public <T> T get(RedisKeyPrefix prefix, String key, Class<T> clazz) {
        T result;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realKey = prefix.getPrefix();
            String strValue = jedis.get(realKey + key);
            result = stringToT(strValue, clazz);
        } finally {
            returnToPool(jedis);
        }
        return result;
    }

    public static <T> T stringToT(String value, Class<T> clazz) {

        if (clazz == int.class || clazz == Integer.class) {
            return (T)Integer.valueOf(value);
        } else if (clazz == long.class || clazz == Long.class) {
            return (T)Long.valueOf(value);
        } else if (clazz == String.class) {
            return (T)value;
        } else {
            return JSON.parseObject(value, clazz);
        }

    }
    // 引入prefix前缀是为了预防
    public  <T> boolean set(RedisKeyPrefix prefix, String key, T value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realKey = prefix.getPrefix();
            int expireTime = prefix.expireSeconds();
            if (expireTime <= 0) {
                jedis.set(realKey + key, TtoString(value));
            } else {
                jedis.setex(realKey + key, expireTime, TtoString(value));
            }

            return true;
        } finally {
            returnToPool(jedis);
        }
    }

    public static  <T> String TtoString(T value) {

        Class clazz = value.getClass();
        if (clazz == int.class || clazz == Integer.class) {
            return "" + value;
        } else if (clazz == long.class || clazz == Long.class) {
            return "" + value;
        } else if (clazz == String.class) {
            return (String)value;
        } else {
            return JSON.toJSONString(value);
        }
    }


    public void returnToPool(Jedis jedis) {
        if (null != jedis) {
            jedis.close();
        }
    }

    public long decr(MiaoShaGoodsKey miaoshaGoodsStock, String goodsId) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realKey = miaoshaGoodsStock.getPrefix();
            return jedis.decr(realKey + goodsId);
        } finally {
            returnToPool(jedis);
        }

    }
}
